package com.key.controller;

import java.sql.Connection;
import java.sql.PreparedStatement;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.key.model.ModifyPassword;
import com.key.model.User;
import com.key.tools.ConnectionPool;

@Controller
@RequestMapping("/sys")
public class SysController {
	@RequestMapping("/modifyPassword")
	public ModelAndView modifyPassword(ModifyPassword mp,
			HttpServletRequest request) {
		ConnectionPool cp = ConnectionPool.getInstance();
		Connection ct = cp.getConnection();
		try {
			if (!mp.getPassword1().equals(mp.getPassword2())) {
				request.setAttribute("result", false);
				request.setAttribute("errorMessage", "两次密码输入不同");
			} else {
				User user = (User) request.getSession().getAttribute("user");
				PreparedStatement ps = ct
						.prepareStatement("update t_user set password = ? where username=?");
				ps.setString(1, mp.getPassword1());
				ps.setString(2, user.getLoginName());
				int r = ps.executeUpdate();
				if (r > 0) {
					request.setAttribute("result", true);
				} else {
					request.setAttribute("result", false);
					request.setAttribute("errorMessage", "");
				}
				ps.close();
			}
		} catch (Exception e) {
			request.setAttribute("result", false);
			request.setAttribute("errorMessage", e.getMessage());
		} finally {
			try {
				ct.close();
			} catch (Exception e) {
				request.setAttribute("result", false);
				request.setAttribute("errorMessage", e.getMessage());
			}
		}
		return new ModelAndView("/jsp/sys/result");
	}
}
